idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
24,100
public static void move ( final Object ar , final int pos , final int off , final int l ) { System . arraycopy ( ar , pos , ar , pos + off , l ) ; }
Moves entries inside an array .
41
7
24,101
public static < T > T [ ] delete ( final T [ ] ar , final int p ) { final int s = ar . length - 1 ; move ( ar , p + 1 , - 1 , s - p ) ; return Arrays . copyOf ( ar , s ) ; }
Removes an array entry at the specified position .
60
10
24,102
private static void swap ( final int [ ] arr , final int a , final int b ) { final int c = arr [ a ] ; arr [ a ] = arr [ b ] ; arr [ b ] = c ; }
Swaps two entries of the given int array .
47
10
24,103
private static Shape createArrowShape ( int w , int y0 , int y1 ) { Path2D path = new Path2D . Double ( ) ; path . moveTo ( 0 , y0 ) ; if ( ( w & 1 ) == 0 ) { path . lineTo ( w >> 1 , y1 ) ; } else { int c = w >> 1 ; path . lineTo ( c , y1 ) ; path . lineTo ( c + 1 , y1 ) ; } path . lineTo ( w , y0 ) ; path . closePath ( ) ; return path ; }
Creates a triangle shape with the given coordinates
126
9
24,104
private static SortOrder getSortOrder ( JTable table , int column ) { List < ? extends SortKey > sortKeys = table . getRowSorter ( ) . getSortKeys ( ) ; for ( int i = 0 ; i < sortKeys . size ( ) ; i ++ ) { SortKey sortKey = sortKeys . get ( i ) ; if ( sortKey . getColumn ( ) == table . convertColumnIndexToModel ( column ) ) { return sortKey . getSortOrder ( ) ; } } return null ; }
Returns the sort order of the specified column in the given table or null if the column is not sorted
112
20
24,105
private static int getSortPriority ( JTable table , int column ) { List < ? extends SortKey > sortKeys = table . getRowSorter ( ) . getSortKeys ( ) ; for ( int i = 0 ; i < sortKeys . size ( ) ; i ++ ) { SortKey sortKey = sortKeys . get ( i ) ; if ( sortKey . getColumn ( ) == table . convertColumnIndexToModel ( column ) ) { return i ; } } return - 1 ; }
Returns the sort priority of the specified column in the given table where 0 means the highest priority and - 1 means that the column is not sorted .
106
29
24,106
public void init ( final Context context , final Handler mainThreadHandler , final Logger logger , final PushTokenProvider provider , final PushTokenListener tokenListener , final PushMessageListener messageListener ) { log = logger ; this . provider = provider != null ? provider : ( ) -> FirebaseInstanceId . getInstance ( ) . getToken ( ) ; registerPushReceiver ( mainThreadHandler , context , this . provider , tokenListener , messageListener ) ; }
Initialise PushManager .
95
5
24,107
private void registerPushReceiver ( final Handler mainThreadHandler , final Context context , PushTokenProvider provider , final PushTokenListener tokenListener , final PushMessageListener messageListener ) { IntentFilter filter = new IntentFilter ( ) ; filter . addAction ( IDService . ACTION_REFRESH_PUSH ) ; filter . addAction ( PushService . ACTION_PUSH_MESSAGE ) ; receiver = new PushBroadcastReceiver ( mainThreadHandler , provider , tokenListener , messageListener ) ; LocalBroadcastManager . getInstance ( context . getApplicationContext ( ) ) . registerReceiver ( receiver , filter ) ; }
Register local broadcast listener for refreshed push tokens and push messages .
133
12
24,108
boolean checkAvailablePush ( Context context ) { int connectionStatus = GoogleApiAvailability . getInstance ( ) . isGooglePlayServicesAvailable ( context ) ; if ( connectionStatus == ConnectionResult . SUCCESS ) { log . i ( "Google Play Services are available on this device." ) ; return true ; } else { if ( GoogleApiAvailability . getInstance ( ) . isUserResolvableError ( connectionStatus ) ) { log . e ( "Google Play Services is probably not up to date. User recoverable Error Code is " + connectionStatus ) ; } else { log . e ( "This device is not supported by Google Play Services." ) ; } return false ; } }
Checks if Google Play Services is available on the device .
145
12
24,109
private static Object [ ] [ ] getDataProviderContent ( final Method meth , final Object toInvoke ) { Object [ ] [ ] res ; try { res = ( Object [ ] [ ] ) meth . invoke ( toInvoke ) ; } catch ( IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { throw new IllegalArgumentException ( "Method " + meth + " as data provider throws an exception on invocation" ) ; } return res ; }
Getting the content of a dataprovider .
99
10
24,110
public void add ( final Class < ? > clazz ) { if ( this . clazzes . contains ( clazz ) ) { throw new IllegalArgumentException ( "Only one class-instance per benchmark allowed" ) ; } else { this . clazzes . add ( clazz ) ; } }
Adding a class to bench to this benchmark . This class should contain benchmarkable methods otherwise it will be ignored .
64
22
24,111
public void add ( final Object obj ) { final Class < ? > clazz = obj . getClass ( ) ; if ( this . clazzes . contains ( clazz ) ) { throw new IllegalArgumentException ( "Only one class-instance per benchmark allowed" ) ; } else { this . clazzes . add ( clazz ) ; this . objects . add ( obj ) ; } }
Adding a already instantiated objects to benchmark . Per benchmark only one objects of each class is allowed .
84
20
24,112
public Map < BenchmarkMethod , Integer > getNumberOfMethodsAndRuns ( ) throws PerfidixMethodCheckException { final Map < BenchmarkMethod , Integer > returnVal = new HashMap < BenchmarkMethod , Integer > ( ) ; // instantiate objects, just for getting runs final List < BenchmarkMethod > meths = getBenchmarkMethods ( ) ; for ( final BenchmarkMethod meth : meths ) { // TODO respect data provider int numberOfRuns = BenchmarkMethod . getNumberOfAnnotatedRuns ( meth . getMethodToBench ( ) ) ; if ( numberOfRuns == Bench . NONE_RUN ) { numberOfRuns = conf . getRuns ( ) ; } returnVal . put ( meth , numberOfRuns ) ; } return returnVal ; }
Getting the number of all methods and all runs
174
9
24,113
public BenchmarkResult run ( ) { final BenchmarkResult res = new BenchmarkResult ( conf . getListener ( ) ) ; BenchmarkExecutor . initialize ( conf , res ) ; // instantiate methods final Map < Class < ? > , Object > instantiatedObjs = instantiateObjects ( res ) ; // getting Benchmarkables try { final List < BenchmarkElement > elements = getBenchmarkElements ( instantiatedObjs ) ; // arranging them final AbstractMethodArrangement arrangement = AbstractMethodArrangement . getMethodArrangement ( elements , conf . getArrangement ( ) ) ; // getting the mapping and executing beforemethod final Map < Class < ? > , Object > objectsToExecute = executeBeforeBenchClass ( instantiatedObjs , res ) ; // executing the bench for the arrangement for ( final BenchmarkElement elem : arrangement ) { // invoking gc if possible if ( RAN . nextDouble ( ) < conf . getGcProb ( ) ) { System . gc ( ) ; } final BenchmarkExecutor exec = BenchmarkExecutor . getExecutor ( elem ) ; final Object obj = objectsToExecute . get ( elem . getMeth ( ) . getMethodToBench ( ) . getDeclaringClass ( ) ) ; // check needed because of failed initialization of objects if ( obj != null ) { exec . executeBeforeMethods ( obj ) ; exec . executeBench ( obj , elem . getParameter ( ) ) ; exec . executeAfterMethods ( obj ) ; } } // cleaning up methods to benchmark tearDownObjectsToExecute ( objectsToExecute , res ) ; } catch ( PerfidixMethodCheckException exc ) { res . addException ( exc ) ; } return res ; }
Running this benchmark
374
3
24,114
private Map < Class < ? > , Object > executeBeforeBenchClass ( final Map < Class < ? > , Object > instantiatedObj , final BenchmarkResult res ) { final Map < Class < ? > , Object > returnVal = new Hashtable < Class < ? > , Object > ( ) ; // invoking before bench class for ( final Class < ? > clazz : instantiatedObj . keySet ( ) ) { final Object objectToUse = instantiatedObj . get ( clazz ) ; // ..the search for the beforeClassMeth begins... Method beforeClassMeth = null ; boolean continueVal = true ; try { beforeClassMeth = BenchmarkMethod . findAndCheckAnyMethodByAnnotation ( clazz , BeforeBenchClass . class ) ; // ... and if this search is throwing an exception, the // exception will be added and a flag is set to break up } catch ( final PerfidixMethodCheckException e ) { res . addException ( e ) ; continueVal = false ; } // if everything worked well... if ( continueVal ) { if ( beforeClassMeth == null ) { // ...either the objects is directly mapped to the class // for executing the benches returnVal . put ( clazz , objectToUse ) ; } else { // ... or the beforeMethod will be executed and a // possible exception stored to the result... final PerfidixMethodCheckException beforeByCheck = BenchmarkExecutor . checkMethod ( objectToUse , BeforeBenchClass . class , beforeClassMeth ) ; if ( beforeByCheck == null ) { final PerfidixMethodInvocationException beforeByInvok = BenchmarkExecutor . invokeMethod ( objectToUse , BeforeBenchClass . class , beforeClassMeth ) ; if ( beforeByInvok == null ) { returnVal . put ( clazz , objectToUse ) ; } else { res . addException ( beforeByInvok ) ; } } else { res . addException ( beforeByCheck ) ; } } } } return returnVal ; }
Executing beforeBenchClass if present .
429
8
24,115
List < BenchmarkMethod > getBenchmarkMethods ( ) throws PerfidixMethodCheckException { // Generating Set for returnVal final List < BenchmarkMethod > elems = new ArrayList < BenchmarkMethod > ( ) ; // Getting all Methods and testing if its benchmarkable for ( final Class < ? > clazz : clazzes ) { for ( final Method meth : clazz . getDeclaredMethods ( ) ) { // Check if benchmarkable, if so, insert to returnVal; if ( BenchmarkMethod . isBenchmarkable ( meth ) ) { final BenchmarkMethod benchmarkMeth = new BenchmarkMethod ( meth ) ; elems . add ( benchmarkMeth ) ; } } } return elems ; }
Getting all Benchmarkable methods out of the registered class .
154
12
24,116
private List < BenchmarkElement > getBenchmarkElements ( final Map < Class < ? > , Object > paramObjs ) throws PerfidixMethodCheckException { final List < BenchmarkElement > elems = new ArrayList < BenchmarkElement > ( ) ; final List < BenchmarkMethod > meths = getBenchmarkMethods ( ) ; for ( final BenchmarkMethod meth : meths ) { final Method dataProv = meth . getDataProvider ( ) ; // Test if benchmark is parameterized. If not.. if ( dataProv == null ) { // ...simple execute the benchrun on the base of the runs set... int numberOfRuns = BenchmarkMethod . getNumberOfAnnotatedRuns ( meth . getMethodToBench ( ) ) ; if ( numberOfRuns == Bench . NONE_RUN ) { numberOfRuns = conf . getRuns ( ) ; } // ...and adding this number of // elements to the set to be evaluated. for ( int i = 0 ; i < numberOfRuns ; i ++ ) { elems . add ( new BenchmarkElement ( meth ) ) ; } } // If the method is parameterized... else { // ..get the parameters final Object [ ] [ ] dataProvider = getDataProviderContent ( dataProv , paramObjs . get ( meth . getMethodToBench ( ) . getDeclaringClass ( ) ) ) ; for ( final Object [ ] parameterSet : dataProvider ) { elems . add ( new BenchmarkElement ( meth , parameterSet ) ) ; } // TODO continue over here } } return elems ; }
Getting all benchmarkable objects out of the registered classes with the annotated number of runs .
342
18
24,117
private NiceTable generateMeterResult ( final String columnDesc , final AbstractMeter meter , final AbstractResult result , final NiceTable input ) { input . addRow ( new String [ ] { columnDesc , meter . getUnit ( ) , AbstractOutput . format ( result . sum ( meter ) ) , AbstractOutput . format ( result . min ( meter ) ) , AbstractOutput . format ( result . max ( meter ) ) , AbstractOutput . format ( result . mean ( meter ) ) , AbstractOutput . format ( result . getStandardDeviation ( meter ) ) , new StringBuilder ( "[" ) . append ( AbstractOutput . format ( result . getConf05 ( meter ) ) ) . append ( "-" ) . append ( AbstractOutput . format ( result . getConf95 ( meter ) ) ) . append ( "]" ) . toString ( ) , AbstractOutput . format ( result . getResultSet ( meter ) . size ( ) ) } ) ; return input ; }
Generating the results for a given table .
204
9
24,118
private NiceTable generateHeader ( final NiceTable table ) { table . addHeader ( "Benchmark" ) ; table . addRow ( new String [ ] { "-" , "unit" , "sum" , "min" , "max" , "avg" , "stddev" , "conf95" , "runs" } ) ; return table ; }
Generating header for a given table .
78
8
24,119
public RestApi initialiseRestClient ( int logLevelNet , APIConfig . BaseURIs baseURIs ) { AuthManager authManager = new AuthManager ( ) { @ Override protected Observable < SessionData > restartSession ( ) { return reAuthenticate ( ) ; } } ; restClient = new RestClient ( new OkHttpAuthenticator ( authManager ) , logLevelNet , baseURIs . getService ( ) . toString ( ) ) ; service = restClient . getService ( ) ; setService ( service ) ; return service ; }
Initialise REST API client .
119
6
24,120
public Observable < ComapiResult < Void > > endSession ( ) { if ( isSessionValid ( ) ) { return wrapObservable ( sessionController . endSession ( ) . map ( mapToComapiResult ( ) ) ) ; } else { //return Observable.onError(getSessionStateErrorDescription()); return Observable . just ( null ) ; } }
Ends currently active session .
79
6
24,121
public Observable < Pair < SessionData , ComapiResult < Void > > > updatePushToken ( ) { final SessionData session = dataMgr . getSessionDAO ( ) . session ( ) ; if ( isSessionValid ( session ) ) { return wrapObservable ( Observable . create ( ( Observable . OnSubscribe < String > ) sub -> { String token = dataMgr . getDeviceDAO ( ) . device ( ) . getPushToken ( ) ; if ( TextUtils . isEmpty ( token ) ) { token = pushMgr . getPushToken ( ) ; if ( ! TextUtils . isEmpty ( token ) ) { dataMgr . getDeviceDAO ( ) . setPushToken ( token ) ; } } sub . onNext ( token ) ; sub . onCompleted ( ) ; } ) . concatMap ( token -> sessionController . doUpdatePush ( session , token ) . map ( mapToComapiResult ( ) ) ) . map ( result -> new Pair <> ( session , result ) ) ) ; } else { return Observable . error ( getSessionStateErrorDescription ( ) ) ; } }
Gets an observable task for push token registration . Will emit FCM push token for provided senderId .
244
21
24,122
public Observable < ComapiResult < ConversationEventsResponse > > queryConversationEvents ( @ NonNull final String conversationId , @ NonNull final Long from , @ NonNull final Integer limit ) { final String token = getToken ( ) ; if ( sessionController . isCreatingSession ( ) ) { return getTaskQueue ( ) . queueQueryConversationEvents ( conversationId , from , limit ) ; } else if ( TextUtils . isEmpty ( token ) ) { return Observable . error ( getSessionStateErrorDescription ( ) ) ; } else { return doQueryConversationEvents ( token , conversationId , from , limit ) ; } }
Query conversation events .
138
4
24,123
public Observable < ComapiResult < Void > > isTyping ( @ NonNull final String conversationId ) { final String token = getToken ( ) ; if ( sessionController . isCreatingSession ( ) || TextUtils . isEmpty ( token ) ) { return Observable . error ( getSessionStateErrorDescription ( ) ) ; } else { return doIsTyping ( token , conversationId , true ) ; } }
Send user is typing .
89
5
24,124
private boolean isSessionValid ( final SessionData session ) { return ! sessionController . isCreatingSession ( ) && session != null && session . getSessionId ( ) != null && session . getAccessToken ( ) != null ; }
Is session successfully created .
48
5
24,125
< E > Observable < E > wrapObservable ( Observable < E > obs ) { return obs . subscribeOn ( Schedulers . io ( ) ) . observeOn ( Schedulers . io ( ) ) ; }
Sets schedulers for API calls observables .
49
11
24,126
private SortKey toggle ( SortKey key ) { if ( key . getSortOrder ( ) == SortOrder . ASCENDING ) { return new SortKey ( key . getColumn ( ) , SortOrder . DESCENDING ) ; } return new SortKey ( key . getColumn ( ) , SortOrder . ASCENDING ) ; }
Toggle the given key between ASCENDING and DESCENDING
71
14
24,127
private void init ( ) { TreeNode delegateRoot = null ; if ( delegate != null ) { delegateRoot = ( TreeNode ) delegate . getRoot ( ) ; } thisToDelegate . clear ( ) ; delegateToThis . clear ( ) ; if ( delegateRoot == null ) { root = null ; return ; } root = createNode ( delegateRoot ) ; }
Initialize this tree model
77
5
24,128
private FilteredTreeNode createNode ( final TreeNode delegateNode ) { FilteredTreeNode node = new FilteredTreeNode ( this , delegateNode ) ; delegateToThis . put ( delegateNode , node ) ; thisToDelegate . put ( node , delegateNode ) ; @ SuppressWarnings ( "unchecked" ) Enumeration < ? extends TreeNode > delegateChildren = delegateNode . children ( ) ; while ( delegateChildren . hasMoreElements ( ) ) { TreeNode delegateChild = delegateChildren . nextElement ( ) ; createNode ( delegateChild ) ; } return node ; }
Recursively create the node for the given delegate node and its children .
127
15
24,129
protected void fireTreeStructureChanged ( Object source , Object [ ] path , int [ ] childIndices , Object [ ] children ) { for ( TreeModelListener listener : treeModelListeners ) { listener . treeStructureChanged ( new TreeModelEvent ( source , path , childIndices , children ) ) ; } }
Fires a treeStructureChanged event
68
8
24,130
@ Bench ( runs = RUNS , beforeEachRun = "intArrayListAdd" ) public void intArrayListGet ( ) { for ( int i = 0 ; i < list . size ( ) ; i ++ ) { list . get ( i ) ; } }
bench for retrieving an element at a specified index
56
9
24,131
@ Bench ( runs = RUNS ) public void arrayListAdd ( ) { arrayList = new ArrayList < Integer > ( ) ; for ( final int i : intData ) { arrayList . add ( i ) ; } }
bench for adding data to the [
48
7
24,132
@ Bench ( runs = RUNS ) public void vectorAdd ( ) { vector = new Vector < Integer > ( ) ; for ( final int i : intData ) { vector . add ( i ) ; } }
benchmark for adding data to [
44
7
24,133
public boolean registerClasses ( final String ... classNames ) throws SocketViewException { try { benchmark = Perfidix . setUpBenchmark ( classNames , benchmark ) ; final Map < BenchmarkMethod , Integer > vals = benchmark . getNumberOfMethodsAndRuns ( ) ; return view . initProgressView ( vals ) ; } catch ( final ClassNotFoundException | PerfidixMethodCheckException e2 ) { return view . updateErrorInElement ( e2 . toString ( ) , e2 ) ; } }
Registering all classes and getting a mapping with the Methods and the corresponding overall runs
114
16
24,134
public boolean runBenchmark ( ) throws SocketViewException { final BenchmarkResult res = benchmark . run ( ) ; new TabularSummaryOutput ( ) . visitBenchmark ( res ) ; view . finished ( ) ; return true ; }
This method starts the bench progress with the registered classes .
49
11
24,135
public static void adjustColumnWidths ( JTable table , int maxWidth ) { final int safety = 20 ; for ( int c = 0 ; c < table . getColumnCount ( ) ; c ++ ) { TableColumn column = table . getColumnModel ( ) . getColumn ( c ) ; TableCellRenderer headerRenderer = column . getHeaderRenderer ( ) ; if ( headerRenderer == null ) { headerRenderer = table . getTableHeader ( ) . getDefaultRenderer ( ) ; } Component headerComponent = headerRenderer . getTableCellRendererComponent ( table , column . getHeaderValue ( ) , false , false , 0 , 0 ) ; int width = headerComponent . getPreferredSize ( ) . width ; for ( int r = 0 ; r < table . getRowCount ( ) ; r ++ ) { TableCellRenderer cellRenderer = table . getCellRenderer ( r , c ) ; Component cellComponent = cellRenderer . getTableCellRendererComponent ( table , table . getValueAt ( r , c ) , false , false , r , c ) ; Dimension d = cellComponent . getPreferredSize ( ) ; //System.out.println( // "Preferred is "+d.width+" for "+cellComponent); width = Math . max ( width , d . width ) ; } column . setPreferredWidth ( Math . min ( maxWidth , width + safety ) ) ; } }
Adjust the preferred widths of the columns of the given table depending on the contents of the cells and headers .
320
22
24,136
public static void scrollToRow ( JTable table , int row ) { Rectangle visibleRect = table . getVisibleRect ( ) ; Rectangle cellRect = table . getCellRect ( row , 0 , true ) ; Rectangle r = new Rectangle ( visibleRect . x , cellRect . y , visibleRect . width , cellRect . height ) ; table . scrollRectToVisible ( r ) ; }
Scroll the given table so that the specified row is visible .
88
12
24,137
public static Set < Integer > convertRowIndicesToView ( JTable table , Iterable < ? extends Integer > modelRows ) { Set < Integer > viewRows = new LinkedHashSet < Integer > ( ) ; for ( Integer modelRow : modelRows ) { int viewRow = table . convertRowIndexToView ( modelRow ) ; viewRows . add ( viewRow ) ; } return viewRows ; }
Convert all of the given model row indices to view row indices for the given table
92
17
24,138
public static Set < Integer > convertRowIndicesToModel ( JTable table , Iterable < ? extends Integer > viewRows ) { Set < Integer > modelRows = new LinkedHashSet < Integer > ( ) ; for ( Integer viewRow : viewRows ) { int modelRow = table . convertRowIndexToModel ( viewRow ) ; modelRows . add ( modelRow ) ; } return modelRows ; }
Convert all of the given view row indices to model row indices for the given table
92
17
24,139
private static void setDerivedFont ( JTable t , float size ) { t . setFont ( t . getFont ( ) . deriveFont ( size ) ) ; t . getTableHeader ( ) . setFont ( t . getTableHeader ( ) . getFont ( ) . deriveFont ( size ) ) ; }
Set a derived font with the given size for the given table and its header
67
15
24,140
private static double computeLuminance ( int argb ) { int r = ( argb >> 16 ) & 0xFF ; int g = ( argb >> 8 ) & 0xFF ; int b = ( argb ) & 0xFF ; double nr = Math . pow ( ( r / 255.0 ) , 2.2 ) ; double ng = Math . pow ( ( g / 255.0 ) , 2.2 ) ; double nb = Math . pow ( ( b / 255.0 ) , 2.2 ) ; double y = 0.2126 * nr + 0.7151 * ng + 0.0721 * nb ; return y ; }
Returns the luminance of the given ARGB color
145
10
24,141
public void log ( final String tag , final int logLevel , final String msg , final Throwable exception ) { if ( aConsole != null ) { aConsole . appendLog ( tag , logLevel , msg , exception ) ; } if ( aFile != null ) { aFile . appendLog ( tag , logLevel , msg , exception ) ; } }
Logs message using defined appender .
74
8
24,142
private void dispatchMessage ( PushMessageListener listener , RemoteMessage message ) { if ( listener != null ) { mainThreadHandler . post ( ( ) -> listener . onMessageReceived ( message ) ) ; } }
Dispatch received push message to external listener .
44
8
24,143
private OkHttpClient createOkHttpClient ( OkHttpAuthenticator authenticator , int logLevel ) { OkHttpClient . Builder builder = new OkHttpClient . Builder ( ) . addInterceptor ( loggingInterceptor ( logLevel ) ) . connectTimeout ( CONNECT_TIMEOUT , TimeUnit . SECONDS ) . writeTimeout ( WRITE_TIMEOUT , TimeUnit . SECONDS ) . readTimeout ( READ_TIMEOUT , TimeUnit . SECONDS ) . authenticator ( authenticator ) ; return builder . build ( ) ; }
Create and configure OkHTTP client .
114
7
24,144
private HttpLoggingInterceptor loggingInterceptor ( int logLevel ) { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor ( ) ; switch ( logLevel ) { case LogLevelConst . DEBUG : interceptor . setLevel ( HttpLoggingInterceptor . Level . BODY ) ; break ; default : interceptor . setLevel ( HttpLoggingInterceptor . Level . NONE ) ; break ; } return interceptor ; }
Create and configure HTTP interceptor that will log the bodies of requests and responses .
98
16
24,145
private Gson createGson ( ) { GsonBuilder gsonBuilder = new GsonBuilder ( ) . disableHtmlEscaping ( ) . setLenient ( ) . addSerializationExclusionStrategy ( new ExclusionStrategy ( ) { @ Override public boolean shouldSkipField ( FieldAttributes f ) { return f . getAnnotation ( SerializedName . class ) == null ; } @ Override public boolean shouldSkipClass ( Class < ? > clazz ) { return false ; } } ) ; return gsonBuilder . create ( ) ; }
Create Gson converter for the service .
118
8
24,146
void initialise ( @ NonNull final Application application , CallbackAdapter adapter , Callback < ComapiClient > callback ) { this . adapter = adapter ; adapter . adapt ( super . initialise ( application , this , adapter ) , callback ) ; }
Initialise Comapi client instance .
52
7
24,147
boolean clearAll ( ) { SharedPreferences . Editor editor = sharedPreferences . edit ( ) ; Map < String , ? > all = sharedPreferences . getAll ( ) ; //noinspection Convert2streamapi for ( String key : all . keySet ( ) ) { editor . remove ( key ) ; } return editor . commit ( ) ; }
Clear all entries in internal shared preferences file .
76
9
24,148
boolean clear ( String key ) { SharedPreferences . Editor editor = sharedPreferences . edit ( ) ; editor . remove ( key ) ; return editor . commit ( ) ; }
Clear entry .
38
3
24,149
public void addHeader ( final String title , final char mark , final Alignment orientation ) { final Header header = new Header ( title , mark , orientation , this ) ; rows . add ( header ) ; }
Adds a header row to the table . can be used to give a table some title .
43
18
24,150
public void addRow ( final String [ ] data ) { if ( anyStringContainsNewLine ( data ) ) { final String [ ] [ ] theMatrix = Util . createMatrix ( data ) ; for ( int i = 0 ; i < theMatrix . length ; i ++ ) { addRow ( theMatrix [ i ] ) ; } } else { final Row myRow = new Row ( this , data ) ; rows . add ( myRow ) ; } }
Adds a string row . checks that the strings added do not contain newlines because if so it has to split them in order to make them fit the row .
98
32
24,151
void updateColumnWidth ( final int index , final int newSize ) { columnLengths [ index ] = Math . max ( columnLengths [ index ] , newSize ) ; }
Performs an update on the column lengths .
38
9
24,152
private int getRowWidth ( ) { int returnVal = 1 ; if ( rows . size ( ) < 1 ) { returnVal = 0 ; } for ( int i = 0 ; i < rows . size ( ) ; i ++ ) { if ( rows . get ( i ) instanceof Row ) { returnVal = ( ( Row ) rows . get ( i ) ) . getRowWidth ( ) ; } } return returnVal ; }
Returns the row width .
91
5
24,153
private boolean anyStringContainsNewLine ( final String [ ] data ) { boolean returnVal = false ; for ( int i = 0 ; i < data . length ; i ++ ) { if ( Util . containsNewlines ( data [ i ] ) ) { returnVal = true ; } } return returnVal ; }
Tests whether any string contains a newline symbol .
67
11
24,154
public < T > T parse ( String text , Class < T > clazz ) { return gson . fromJson ( text , clazz ) ; }
Parse json to POJO .
33
7
24,155
public < T > T parse ( JsonObject obj , Class < T > clazz ) { return gson . fromJson ( obj , clazz ) ; }
Parse JsonObject to POJO .
35
9
24,156
public static int showValidatedTextInputDialog ( Window parent , String title , JComponent mainComponent , JTextComponent textComponent , Predicate < String > validInputPredicate ) { JButton okButton = new JButton ( "Ok" ) ; String text = textComponent . getText ( ) ; boolean valid = validInputPredicate . test ( text ) ; okButton . setEnabled ( valid ) ; JButton cancelButton = new JButton ( "Cancel" ) ; Object [ ] options = new Object [ ] { okButton , cancelButton } ; JOptionPane optionPane = new JOptionPane ( mainComponent , JOptionPane . PLAIN_MESSAGE , JOptionPane . OK_CANCEL_OPTION , null , options , okButton ) ; okButton . addActionListener ( e -> optionPane . setValue ( okButton ) ) ; cancelButton . addActionListener ( e -> optionPane . setValue ( cancelButton ) ) ; AncestorListener focussingAncestorListener = new AncestorListener ( ) { @ Override public void ancestorAdded ( AncestorEvent event ) { textComponent . requestFocus ( ) ; } @ Override public void ancestorRemoved ( AncestorEvent event ) { // Nothing to do here } @ Override public void ancestorMoved ( AncestorEvent event ) { // Nothing to do here } } ; textComponent . addAncestorListener ( focussingAncestorListener ) ; DocumentListener documentListener = new DocumentListener ( ) { @ Override public void insertUpdate ( DocumentEvent e ) { updateButtonState ( ) ; } @ Override public void removeUpdate ( DocumentEvent e ) { updateButtonState ( ) ; } @ Override public void changedUpdate ( DocumentEvent e ) { updateButtonState ( ) ; } protected void updateButtonState ( ) { String text = textComponent . getText ( ) ; boolean valid = validInputPredicate . test ( text ) ; okButton . setEnabled ( valid ) ; } } ; Document document = textComponent . getDocument ( ) ; document . addDocumentListener ( documentListener ) ; JDialog dialog = optionPane . createDialog ( parent , title ) ; dialog . pack ( ) ; dialog . setResizable ( true ) ; dialog . setVisible ( true ) ; document . removeDocumentListener ( documentListener ) ; textComponent . removeAncestorListener ( focussingAncestorListener ) ; Object selectedValue = optionPane . getValue ( ) ; if ( selectedValue == null ) { return JOptionPane . CLOSED_OPTION ; } return Arrays . asList ( options ) . indexOf ( selectedValue ) ; }
Create a new input dialog that performs validation .
569
9
24,157
private void handleOnResume ( Context context ) { if ( wasInBackground . get ( ) ) { startTime . set ( System . currentTimeMillis ( ) ) ; isApplicationForegrounded . set ( true ) ; listener . onForegrounded ( context ) ; } stopActivityTransitionTimer ( ) ; }
React to activity onResume event .
68
9
24,158
@ SuppressWarnings ( "resource" ) protected static final String format ( final double toFormat ) { return new Formatter ( Locale . US ) . format ( FLOATFORMAT , toFormat ) . toString ( ) ; }
Formats a double .
52
5
24,159
private void rollOverFiles ( ) { Context context = appContextRef . get ( ) ; if ( context != null ) { File dir = context . getFilesDir ( ) ; File mainFile = new File ( dir , name ( 1 ) ) ; if ( mainFile . exists ( ) ) { float fileSize = mainFile . length ( ) ; fileSize = fileSize / 1024.0f ; //In kilobytes if ( fileSize > fileSizeLimitKb ) { File file ; File target ; file = new File ( dir , name ( maxFiles ) ) ; if ( file . exists ( ) ) { file . delete ( ) ; } for ( int i = maxFiles - 1 ; i > 0 ; i -- ) { file = new File ( dir , name ( i ) ) ; if ( file . exists ( ) ) { target = new File ( dir , name ( i + 1 ) ) ; file . renameTo ( target ) ; } } } } } }
Keep the maximum size of log files close to maximum value . Logs are cached if the size of the currently used log file exceeds max value .
206
29
24,160
private Observable < String > loadLogsObservable ( ) { return Observable . fromCallable ( ( ) -> { StringBuilder sb = new StringBuilder ( ) ; Context context = appContextRef . get ( ) ; if ( context != null ) { synchronized ( sharedLock ) { try { File dir = context . getFilesDir ( ) ; String line ; for ( int i = 1 ; i <= maxFiles ; i ++ ) { File file = new File ( dir , name ( i ) ) ; if ( file . exists ( ) ) { inputStream = new FileInputStream ( file ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( inputStream ) ) ; while ( ( line = reader . readLine ( ) ) != null ) { sb . append ( line ) . append ( ' ' ) ; } reader . close ( ) ; } } } catch ( Exception e ) { throw Exceptions . propagate ( e ) ; } finally { sharedLock . notifyAll ( ) ; } } } return sb . toString ( ) ; } ) ; }
Gets rx observable that reads the log files and appends to string .
230
16
24,161
public static JScrollPane createVerticalScrollPane ( final JComponent component ) { JScrollPane scrollPane = new JScrollPane ( component ) { /** * Serial UID */ private static final long serialVersionUID = - 177913025197077320L ; @ Override public Dimension getPreferredSize ( ) { Dimension d = super . getPreferredSize ( ) ; if ( super . isPreferredSizeSet ( ) ) { return d ; } JScrollBar scrollBar = getVerticalScrollBar ( ) ; Dimension sd = scrollBar . getPreferredSize ( ) ; d . width += sd . width ; return d ; } @ Override public boolean isValidateRoot ( ) { return false ; } } ; return scrollPane ; }
Creates a JScrollPane for vertically scrolling the given component . The scroll pane will take into account that the vertical scroll bar will be shown when needed and return a preferred size that takes the width of this scroll bar into account so that when the vertical scroll bar appears the contained component can still have its preferred width .
163
64
24,162
public boolean addSorted ( E element ) { boolean added = false ; added = super . add ( element ) ; Comparable < E > cmp = ( Comparable < E > ) element ; for ( int i = size ( ) - 1 ; i > 0 && cmp . compareTo ( get ( i - 1 ) ) < 0 ; i -- ) Collections . swap ( this , i , i - 1 ) ; return added ; }
adds an element to the list in its place based on natural order . allows duplicates .
92
19
24,163
public boolean addSorted ( E element , boolean allowDuplicates ) { boolean added = false ; if ( ! allowDuplicates ) { if ( this . contains ( element ) ) { System . err . println ( "item is a duplicate" ) ; return added ; } } added = super . add ( element ) ; Comparable < E > cmp = ( Comparable < E > ) element ; for ( int i = size ( ) - 1 ; i > 0 && cmp . compareTo ( get ( i - 1 ) ) < 0 ; i -- ) Collections . swap ( this , i , i - 1 ) ; return added ; }
adds an element to the list in its place based on natural order .
136
15
24,164
private void prepareMenu ( Container menu , Component component , int x , int y ) { int n = menu . getComponentCount ( ) ; for ( int i = 0 ; i < n ; i ++ ) { Component menuComponent = popupMenu . getComponent ( i ) ; if ( menuComponent instanceof JMenu ) { JMenu subMenu = ( JMenu ) menuComponent ; prepareMenu ( subMenu , component , x , y ) ; } if ( menuComponent instanceof AbstractButton ) { AbstractButton abstractButton = ( AbstractButton ) menuComponent ; Action action = abstractButton . getAction ( ) ; if ( action != null && action instanceof LocationBasedAction ) { LocationBasedAction locationBasedAction = ( LocationBasedAction ) action ; locationBasedAction . prepareShow ( component , x , y ) ; } } } }
Prepare the given menu recursively with the given parameters
172
12
24,165
private void removeColumn ( int index ) { TableColumn column = tableColumns . get ( index ) ; column . removePropertyChangeListener ( widthListener ) ; tableColumns . remove ( index ) ; JComponent component = customComponents . remove ( index ) ; remove ( component ) ; if ( componentRemover != null ) { componentRemover . accept ( index ) ; } }
Remove the column and the custom component at the given index
80
11
24,166
private void addColumn ( int index ) { TableColumnModel columnModel = getColumnModel ( ) ; TableColumn column = columnModel . getColumn ( index ) ; while ( tableColumns . size ( ) - 1 < index ) { tableColumns . add ( null ) ; } tableColumns . set ( index , column ) ; column . addPropertyChangeListener ( widthListener ) ; JComponent component = componentFactory . apply ( index ) ; while ( customComponents . size ( ) - 1 < index ) { customComponents . add ( null ) ; } customComponents . set ( index , component ) ; add ( component ) ; }
Add the column and the custom component at the given index
135
11
24,167
private void updateCustomComponentBounds ( ) { if ( customComponents == null ) { return ; } if ( table == null ) { return ; } for ( int i = 0 ; i < customComponents . size ( ) ; i ++ ) { JComponent component = customComponents . get ( i ) ; Rectangle rect = getHeaderRect ( i ) ; rect . height = customComponentHeight ; component . setBounds ( rect ) ; } revalidate ( ) ; }
Update the bounds of all custom components based on the current column widths
102
14
24,168
private void initialiseLifecycleObserver ( Application application ) { LifeCycleController . registerLifeCycleObserver ( application , new LifecycleListener ( ) { @ Override public void onForegrounded ( Context context ) { for ( LifecycleListener listener : lifecycleListeners ) { listener . onForegrounded ( context ) ; } } @ Override public void onBackgrounded ( Context context ) { for ( LifecycleListener listener : lifecycleListeners ) { listener . onBackgrounded ( context ) ; } } } ) ; }
Register for application lifecycle callbacks .
115
8
24,169
@ Override public Session getSession ( ) { return state . get ( ) > GlobalState . INITIALISING ? new Session ( dataMgr . getSessionDAO ( ) . session ( ) ) : new Session ( ) ; }
Gets the active session data .
51
7
24,170
private Observable < SessionData > loadSession ( final Boolean initialised ) { if ( initialised ) { final SessionData session = dataMgr . getSessionDAO ( ) . session ( ) ; if ( session != null ) { if ( session . getExpiresOn ( ) > System . currentTimeMillis ( ) ) { state . compareAndSet ( GlobalState . INITIALISED , GlobalState . SESSION_ACTIVE ) ; } else { state . compareAndSet ( GlobalState . INITIALISED , GlobalState . SESSION_OFF ) ; return service . reAuthenticate ( ) . onErrorReturn ( throwable -> { log . w ( "Authentication failure during init." ) ; return session ; } ) ; } } return Observable . create ( sub -> { sub . onNext ( session ) ; sub . onCompleted ( ) ; } ) ; } return Observable . just ( null ) ; }
Loads local session state .
198
6
24,171
public final AbstractMeter [ ] getMeters ( ) { final AbstractMeter [ ] returnVal = new AbstractMeter [ meters . length ] ; System . arraycopy ( meters , 0 , returnVal , 0 , returnVal . length ) ; return returnVal ; }
Getter for member meters
57
5
24,172
public final AbstractOutput [ ] getListener ( ) { final AbstractOutput [ ] returnVal = new AbstractOutput [ listeners . length ] ; System . arraycopy ( listeners , 0 , returnVal , 0 , returnVal . length ) ; return returnVal ; }
Getter for member listeners
53
5
24,173
public < T > void adapt ( @ NonNull final Observable < T > subscriber , @ Nullable final Callback < T > callback ) { subscriber . subscribeOn ( Schedulers . io ( ) ) . observeOn ( AndroidSchedulers . mainThread ( ) ) . subscribe ( new Subscriber < T > ( ) { @ Override public void onCompleted ( ) { } @ Override public void onError ( Throwable e ) { if ( callback != null ) { callback . error ( e ) ; } } @ Override public void onNext ( T result ) { if ( callback != null ) { callback . success ( result ) ; } } } ) ; }
Changes observables into callbacks .
143
7
24,174
private void setSelectionStateOfAll ( State state ) { Objects . requireNonNull ( state , "The state may not be null" ) ; List < Object > allNodes = JTrees . getAllNodes ( getModel ( ) ) ; for ( Object node : allNodes ) { setSelectionState ( node , state ) ; } }
Set the selection state of all nodes to the given state
76
11
24,175
private void setSelectionState ( Object node , State state , boolean propagate ) { Objects . requireNonNull ( state , "The state may not be null" ) ; Objects . requireNonNull ( node , "The node may not be null" ) ; State oldState = selectionStates . put ( node , state ) ; if ( ! state . equals ( oldState ) ) { fireStateChanged ( node , oldState , state ) ; if ( propagate ) { updateSelection ( node ) ; } } repaint ( ) ; }
Set the selection state of the given node
111
8
24,176
private void handleMousePress ( MouseEvent e ) { int row = getRowForLocation ( e . getX ( ) , e . getY ( ) ) ; TreePath path = getPathForLocation ( e . getX ( ) , e . getY ( ) ) ; if ( path == null ) { return ; } TreeCellRenderer cellRenderer = getCellRenderer ( ) ; TreeNode node = ( TreeNode ) path . getLastPathComponent ( ) ; Component cellRendererComponent = cellRenderer . getTreeCellRendererComponent ( CheckBoxTree . this , null , true , true , node . isLeaf ( ) , row , true ) ; Rectangle bounds = getRowBounds ( row ) ; Point localPoint = new Point ( ) ; localPoint . x = e . getX ( ) - bounds . x ; localPoint . y = e . getY ( ) - bounds . y ; Container container = ( Container ) cellRendererComponent ; Component clickedComponent = null ; for ( Component component : container . getComponents ( ) ) { Rectangle b = component . getBounds ( ) ; if ( b . contains ( localPoint ) ) { clickedComponent = component ; } } if ( clickedComponent != null ) { if ( clickedComponent instanceof JCheckBox ) { toggleSelection ( path ) ; repaint ( ) ; } } }
Handle a mouse press and possibly toggle the selection state
297
10
24,177
private void toggleSelection ( TreePath path ) { Object node = path . getLastPathComponent ( ) ; State state = getSelectionState ( node ) ; if ( state == null ) { return ; } if ( state == State . SELECTED ) { setSelectionState ( node , State . UNSELECTED ) ; updateSelection ( node ) ; } else if ( state == State . UNSELECTED ) { setSelectionState ( node , State . SELECTED ) ; updateSelection ( node ) ; } else { setSelectionState ( node , State . SELECTED ) ; updateSelection ( node ) ; } }
Toggle the selection of the given path due to a mouse click
133
13
24,178
private void updateSelection ( Object node ) { State newState = getSelectionState ( node ) ; List < Object > descendants = JTrees . getAllDescendants ( getModel ( ) , node ) ; for ( Object descendant : descendants ) { setSelectionState ( descendant , newState , false ) ; } Object ancestor = JTrees . getParent ( getModel ( ) , node ) ; while ( ancestor != null ) { List < Object > childrenOfAncestor = JTrees . getChildren ( getModel ( ) , ancestor ) ; State stateForAncestor = computeState ( childrenOfAncestor ) ; setSelectionState ( ancestor , stateForAncestor , false ) ; ancestor = JTrees . getParent ( getModel ( ) , ancestor ) ; } }
Update the selection state of the given node based on the state of its children
169
15
24,179
private State computeState ( List < Object > nodes ) { Set < State > set = new LinkedHashSet < State > ( ) ; for ( Object node : nodes ) { set . add ( getSelectionState ( node ) ) ; } // Should never happen while ( set . contains ( null ) ) { logger . warning ( "null found in selection states" ) ; set . remove ( null ) ; } if ( set . size ( ) == 0 ) { // Should never happen logger . warning ( "Empty selection states" ) ; return State . SELECTED ; } if ( set . size ( ) > 1 ) { return State . MIXED ; } return set . iterator ( ) . next ( ) ; }
Compute the state for a node with the given children
150
11
24,180
public void removeFromAccordion ( JComponent component ) { CollapsiblePanel collapsiblePanel = collapsiblePanels . get ( component ) ; if ( collapsiblePanel != null ) { contentPanel . remove ( collapsiblePanel ) ; collapsiblePanels . remove ( component ) ; revalidate ( ) ; } }
Remove the given component from this accordion
68
8
24,181
public void connectSocket ( ) { synchronized ( lock ) { if ( isForegrounded ) { if ( socketConnection == null ) { SocketFactory factory = new SocketFactory ( socketURI , new SocketEventDispatcher ( listener , new Parser ( ) ) . setLogger ( log ) , log ) ; socketConnection = new SocketConnectionController ( new Handler ( Looper . getMainLooper ( ) ) , dataMgr , factory , listener , new RetryStrategy ( 60 , 60000 ) , log ) ; socketConnection . setProxy ( proxyURI ) ; socketConnection . connect ( ) ; } else { socketConnection . connect ( ) ; } socketConnection . setManageReconnection ( true ) ; } lock . notifyAll ( ) ; } }
Create and connect socket .
162
5
24,182
public void disconnectSocket ( ) { synchronized ( lock ) { if ( socketConnection != null ) { socketConnection . setManageReconnection ( false ) ; socketConnection . disconnect ( ) ; } lock . notifyAll ( ) ; } }
Disconnect socket .
51
4
24,183
public LifecycleListener createLifecycleListener ( ) { return new LifecycleListener ( ) { @ Override public void onForegrounded ( Context context ) { synchronized ( lock ) { if ( ! isForegrounded ) { isForegrounded = true ; connectSocket ( ) ; if ( receiver == null ) { receiver = new InternetConnectionReceiver ( socketConnection ) ; } context . registerReceiver ( receiver , new IntentFilter ( ConnectivityManager . CONNECTIVITY_ACTION ) ) ; } lock . notifyAll ( ) ; } } @ Override public void onBackgrounded ( Context context ) { synchronized ( lock ) { if ( isForegrounded ) { isForegrounded = false ; disconnectSocket ( ) ; if ( receiver != null && ! isForegrounded ) { context . unregisterReceiver ( receiver ) ; } } lock . notifyAll ( ) ; } } } ; }
creates application lifecycle and network connectivity callbacks .
190
11
24,184
public boolean initProgressView ( final Map < BenchmarkMethod , Integer > mapping ) throws SocketViewException { if ( mapping != null ) { final Set < BenchmarkMethod > methodSet = mapping . keySet ( ) ; final Map < String , Integer > finalMap = new HashMap < String , Integer > ( ) ; for ( BenchmarkMethod benchmarkMethod : methodSet ) { finalMap . put ( benchmarkMethod . getMethodWithClassName ( ) , mapping . get ( benchmarkMethod ) ) ; } viewStub . initTotalBenchProgress ( finalMap ) ; } return true ; }
This method initializes the values of the eclipse view and resets the progress bar .
123
17
24,185
public boolean updateCurrentElement ( final AbstractMeter meter , final String name ) throws SocketViewException { if ( meter != null && ! regMeterHash ) { registerFirstMeterHash ( meter ) ; } if ( name != null && meter . hashCode ( ) == ( getRegMeter ( ) ) ) { viewStub . updateCurrentRun ( name ) ; } return true ; }
This method notifies the eclipse view which element is currently benched .
83
14
24,186
public boolean updateErrorInElement ( final String name , final Exception exception ) throws SocketViewException { if ( name != null && exception != null ) { if ( exception instanceof AbstractPerfidixMethodException ) { final AbstractPerfidixMethodException exc = ( AbstractPerfidixMethodException ) exception ; viewStub . updateError ( name , exc . getExec ( ) . getClass ( ) . getSimpleName ( ) ) ; } if ( exception instanceof SocketViewException ) { final SocketViewException viewException = ( SocketViewException ) exception ; viewStub . updateError ( name , viewException . getExc ( ) . getClass ( ) . getSimpleName ( ) ) ; } } return true ; }
This method informs the view that an error occurred while benching the current element .
154
16
24,187
static String getLevelTag ( final int logLevel ) { switch ( logLevel ) { case LogLevelConst . FATAL : return LogConstants . TAG_FATAL ; case LogLevelConst . ERROR : return LogConstants . TAG_ERROR ; case LogLevelConst . WARNING : return LogConstants . TAG_WARNING ; case LogLevelConst . INFO : return LogConstants . TAG_INFO ; case LogLevelConst . DEBUG : return LogConstants . TAG_DEBUG ; default : return "[DEFAULT]" ; } }
Gets the string representation of the log level .
111
10
24,188
public String getMessageId ( ) { return ( data != null && data . payload != null ) ? data . payload . messageId : null ; }
Gets id of the updated message .
31
8
24,189
public String getConversationId ( ) { return ( data != null && data . payload != null ) ? data . payload . conversationId : null ; }
Gets id of the conversation for which message was updated .
33
12
24,190
public String getProfileId ( ) { return ( data != null && data . payload != null ) ? data . payload . profileId : null ; }
Gets profile id of the user that changed the message status .
31
13
24,191
public String getTimestamp ( ) { return ( data != null && data . payload != null ) ? data . payload . timestamp : null ; }
Gets time when the message status changed .
30
9
24,192
static String combine ( final String ... args ) { final StringBuilder builder = new StringBuilder ( ) ; for ( final String arg : args ) { builder . append ( arg ) ; } return builder . toString ( ) ; }
Combines an unknown number of Strings to one String .
47
12
24,193
static String implode ( final String glue , final String [ ] what ) { final StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < what . length ; i ++ ) { builder . append ( what [ i ] ) ; if ( i + 1 != what . length ) { builder . append ( glue ) ; } } return builder . toString ( ) ; }
Concantenate a String array what with glue glue .
83
13
24,194
static String repeat ( final String toBeRepeated , final int numTimes ) { final StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < numTimes ; i ++ ) { builder . append ( toBeRepeated ) ; } return builder . toString ( ) ; }
a str_repeat function .
64
6
24,195
private static int numNewLines ( final String toExamine ) { final char [ ] arr = toExamine . toCharArray ( ) ; int result = 0 ; for ( char ch : arr ) { if ( AbstractTabularComponent . NEWLINE . equals ( new String ( new char [ ] { ch } ) ) ) { result ++ ; } } return result ; }
Returns how many new lines are in the string .
79
10
24,196
public static String [ ] [ ] createMatrix ( final String [ ] data ) { int maxNewLines = 0 ; for ( final String col : data ) { maxNewLines = Math . max ( maxNewLines , Util . numNewLines ( col ) ) ; } final String [ ] [ ] matrix = new String [ maxNewLines + 1 ] [ data . length ] ; for ( int col = 0 ; col < data . length ; col ++ ) { final String [ ] exploded = Util . explode ( data [ col ] ) ; for ( int row = 0 ; row < maxNewLines + 1 ; row ++ ) { if ( exploded . length > row ) { matrix [ row ] [ col ] = exploded [ row ] ; } else { matrix [ row ] [ col ] = "" ; } } } return matrix ; }
Creates a matrix according to the number of new lines given into the method .
181
16
24,197
private void handleCommand ( byte b ) throws IOException { if ( b == SE ) { telnetCommand += ( char ) b ; handleNegotiation ( ) ; reset ( ) ; } else if ( isWill || isDo ) { if ( isWill && b == TERMINAL_TYPE ) { socketChannel . write ( ByteBuffer . wrap ( new byte [ ] { IAC , SB , TERMINAL_TYPE , ECHO , IAC , SE } ) ) ; } else if ( b != ECHO && b != GA && b != NAWS ) { telnetCommand += ( char ) b ; socketChannel . write ( ByteBuffer . wrap ( telnetCommand . getBytes ( ) ) ) ; } reset ( ) ; } else if ( isWont || isDont ) { telnetCommand += ( char ) b ; socketChannel . write ( ByteBuffer . wrap ( telnetCommand . getBytes ( ) ) ) ; reset ( ) ; } else if ( isSb ) { telnetCommand += ( char ) b ; } }
Handle telnet command
221
4
24,198
private void handleNegotiation ( ) throws IOException { if ( telnetCommand . contains ( new String ( new byte [ ] { TERMINAL_TYPE } ) ) ) { // IAC SB TERMINAL_TYPE IS XXX IAC SE boolean isSuccess = false ; clientTerminalType = telnetCommand . substring ( 4 , telnetCommand . length ( ) - 2 ) ; for ( String terminalType : terminalTypeMapping . keySet ( ) ) { if ( clientTerminalType . contains ( terminalType ) ) { isSuccess = true ; clientTerminalType = terminalType ; echoPrompt ( ) ; break ; } } if ( ! isSuccess ) { socketChannel . write ( ByteBuffer . wrap ( "TerminalType negotiate failed." . getBytes ( ) ) ) ; throw new RuntimeException ( "TerminalType negotiate failed." ) ; } } }
Handle negotiation of terminal type
185
5
24,199
public String normalizeNumber ( final String number ) { try { final BigDecimal normalizedNumber = parseNumber ( new NumberBuffer ( number ) ) ; if ( normalizedNumber == null ) { return number ; } return normalizedNumber . toBigIntegerExact ( ) . toString ( ) ; } catch ( NumberFormatException | ArithmeticException e ) { // Return the source number in case of error, i.e. malformed input return number ; } }
Normalizes a Japanese number
95
5