idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
153,800
public InputStream openSource ( String packageName , String fileName ) throws IOException { SourceFile sourceFile = findSourceFile ( packageName , fileName ) ; return sourceFile . getInputStream ( ) ; }
Open an input stream on a source file in given package .
153,801
public SourceFile findSourceFile ( String packageName , String fileName ) throws IOException { String platformName = getPlatformName ( packageName , fileName ) ; String canonicalName = getCanonicalName ( packageName , fileName ) ; SourceFile sourceFile = cache . get ( canonicalName ) ; if ( sourceFile != null ) { retur...
Open a source file in given package .
153,802
public int compareSourceLines ( BugCollection lhsCollection , BugCollection rhsCollection , SourceLineAnnotation lhs , SourceLineAnnotation rhs ) { if ( lhs == null || rhs == null ) { return compareNullElements ( lhs , rhs ) ; } int cmp = compareClassesByName ( lhsCollection , rhsCollection , lhs . getClassName ( ) , r...
Compare source line annotations .
153,803
public void process ( ) throws IOException { int pos = 0 ; do { int meta = findNextMeta ( text , pos ) ; if ( meta >= 0 ) { emitLiteral ( text . substring ( pos , meta ) ) ; emitLiteral ( map . getReplacement ( text . substring ( meta , meta + 1 ) ) ) ; pos = meta + 1 ; } else { emitLiteral ( text . substring ( pos , t...
Quote metacharacters in the text .
153,804
private E createUsingConstructor ( ) throws CheckedAnalysisException { Constructor < E > constructor ; try { constructor = databaseClass . getConstructor ( new Class [ 0 ] ) ; } catch ( NoSuchMethodException e ) { return null ; } try { return constructor . newInstance ( new Object [ 0 ] ) ; } catch ( InstantiationExcep...
Try to create the database using a no - arg constructor .
153,805
protected void work ( final IWorkbenchPart part , IResource resource , final List < WorkItem > resources ) { FindBugsJob clearMarkersJob = new ClearMarkersJob ( resource , resources ) ; clearMarkersJob . addJobChangeListener ( new JobChangeAdapter ( ) { public void done ( IJobChangeEvent event ) { refreshViewer ( part ...
Clear the FindBugs markers on each project in the given selection displaying a progress monitor .
153,806
public void pushValue ( ValueType value ) { if ( VERIFY_INTEGRITY && value == null ) { throw new IllegalArgumentException ( ) ; } if ( ! isValid ( ) ) { throw new IllegalStateException ( "accessing top or bottom frame" ) ; } slotList . add ( value ) ; }
Push a value onto the Java operand stack .
153,807
public ValueType popValue ( ) throws DataflowAnalysisException { if ( ! isValid ( ) ) { throw new DataflowAnalysisException ( "accessing top or bottom frame" ) ; } if ( slotList . size ( ) == numLocals ) { throw new DataflowAnalysisException ( "operand stack empty" ) ; } return slotList . remove ( slotList . size ( ) -...
Pop a value off of the Java operand stack .
153,808
public ValueType getTopValue ( ) throws DataflowAnalysisException { if ( ! isValid ( ) ) { throw new DataflowAnalysisException ( "accessing top or bottom frame" ) ; } assert slotList . size ( ) >= numLocals ; if ( slotList . size ( ) == numLocals ) { throw new DataflowAnalysisException ( "operand stack is empty" ) ; } ...
Get the value on the top of the Java operand stack .
153,809
public void getTopStackWords ( ValueType [ ] valueList ) throws DataflowAnalysisException { int stackDepth = getStackDepth ( ) ; if ( valueList . length > stackDepth ) { throw new DataflowAnalysisException ( "not enough values on stack" ) ; } int numSlots = slotList . size ( ) ; for ( int i = numSlots - valueList . len...
Get the values on the top of the Java operand stack . The top stack item is placed at the end of the array so that to restore the values to the stack you would push them in the order they appear in the array .
153,810
public ValueType getStackValue ( int loc ) throws DataflowAnalysisException { if ( ! isValid ( ) ) { throw new DataflowAnalysisException ( "Accessing TOP or BOTTOM frame!" ) ; } int stackDepth = getStackDepth ( ) ; if ( loc >= stackDepth ) { throw new DataflowAnalysisException ( "not enough values on stack: access=" + ...
Get a value on the operand stack .
153,811
public int getStackLocation ( int loc ) throws DataflowAnalysisException { int stackDepth = getStackDepth ( ) ; if ( loc >= stackDepth ) { throw new DataflowAnalysisException ( "not enough values on stack: access=" + loc + ", avail=" + stackDepth ) ; } return slotList . size ( ) - ( loc + 1 ) ; }
Get a the location in the frame of a value on the operand stack .
153,812
public int getInstanceSlot ( Instruction ins , ConstantPoolGen cpg ) throws DataflowAnalysisException { if ( ! isValid ( ) ) { throw new DataflowAnalysisException ( "Accessing invalid frame at " + ins ) ; } int numConsumed = ins . consumeStack ( cpg ) ; if ( numConsumed == Const . UNPREDICTABLE ) { throw new DataflowAn...
Get the slot the object instance referred to by given instruction is located in .
153,813
public int getNumArguments ( InvokeInstruction ins , ConstantPoolGen cpg ) { SignatureParser parser = new SignatureParser ( ins . getSignature ( cpg ) ) ; return parser . getNumParameters ( ) ; }
Get the number of arguments passed to given method invocation .
153,814
public int getNumArgumentsIncludingObjectInstance ( InvokeInstruction ins , ConstantPoolGen cpg ) throws DataflowAnalysisException { int numConsumed = ins . consumeStack ( cpg ) ; if ( numConsumed == Const . UNPREDICTABLE ) { throw new DataflowAnalysisException ( "Unpredictable stack consumption in " + ins ) ; } return...
Get the number of arguments passed to given method invocation including the object instance if the call is to an instance method .
153,815
public BitSet getArgumentSet ( InvokeInstruction invokeInstruction , ConstantPoolGen cpg , DataflowValueChooser < ValueType > chooser ) throws DataflowAnalysisException { BitSet chosenArgSet = new BitSet ( ) ; SignatureParser sigParser = new SignatureParser ( invokeInstruction . getSignature ( cpg ) ) ; for ( int i = 0...
Get set of arguments passed to a method invocation which match given predicate .
153,816
public void clearStack ( ) { if ( ! isValid ( ) ) { throw new IllegalStateException ( "accessing top or bottom frame" ) ; } assert slotList . size ( ) >= numLocals ; if ( slotList . size ( ) > numLocals ) { slotList . subList ( numLocals , slotList . size ( ) ) . clear ( ) ; } }
Clear the Java operand stack . Only local variable slots will remain in the frame .
153,817
public boolean sameAs ( Frame < ValueType > other ) { if ( isTop != other . isTop ) { return false ; } if ( isTop && other . isTop ) { return true ; } if ( isBottom != other . isBottom ) { return false ; } if ( isBottom && other . isBottom ) { return true ; } if ( getNumSlots ( ) != other . getNumSlots ( ) ) { return f...
Return true if this stack frame is the same as the one given as a parameter .
153,818
public void copyFrom ( Frame < ValueType > other ) { lastUpdateTimestamp = other . lastUpdateTimestamp ; slotList = new ArrayList < > ( other . slotList ) ; isTop = other . isTop ; isBottom = other . isBottom ; }
Make this Frame exactly the same as the one given as a parameter .
153,819
public void addAnnotation ( AnnotationValue annotationValue ) { HashMap < ClassDescriptor , AnnotationValue > updatedMap = new HashMap < > ( classAnnotations ) ; updatedMap . put ( annotationValue . getAnnotationClass ( ) , annotationValue ) ; classAnnotations = Util . immutableMap ( updatedMap ) ; }
Destructively add an annotation to the object . In general this is not a great idea since it could cause the same class to appear to have different annotations at different times . However this method is necessary for built - in annotations that FindBugs adds to system classes . As long as we add such annotations early...
153,820
String getResourceName ( String fileName ) { String dirPath = directory . getPath ( ) ; if ( ! fileName . startsWith ( dirPath ) ) { throw new IllegalStateException ( "Filename " + fileName + " not inside directory " + dirPath ) ; } String relativeFileName = fileName . substring ( dirPath . length ( ) ) ; File file = n...
Get the resource name given a full filename .
153,821
private void work ( final IProject project , final String fileName ) { FindBugsJob runFindBugs = new FindBugsJob ( "Saving SpotBugs XML data to " + fileName + "..." , project ) { protected void runWithProgress ( IProgressMonitor monitor ) throws CoreException { BugCollection bugCollection = FindbugsPlugin . getBugColle...
Save the XML result of a FindBugs analysis on the given project displaying a progress monitor .
153,822
protected void printBug ( BugInstance bugInstance ) { if ( showRank ) { int rank = BugRanker . findRank ( bugInstance ) ; outputStream . printf ( "%2d " , rank ) ; } switch ( bugInstance . getPriority ( ) ) { case Priorities . EXP_PRIORITY : outputStream . print ( "E " ) ; break ; case Priorities . LOW_PRIORITY : outpu...
Print bug in one - line format .
153,823
public ClassFeatureSet initialize ( JavaClass javaClass ) { this . className = javaClass . getClassName ( ) ; this . isInterface = javaClass . isInterface ( ) ; addFeature ( CLASS_NAME_KEY + transformClassName ( javaClass . getClassName ( ) ) ) ; for ( Method method : javaClass . getMethods ( ) ) { if ( ! isSynthetic (...
Initialize from given JavaClass .
153,824
private boolean overridesSuperclassMethod ( JavaClass javaClass , Method method ) { if ( method . isStatic ( ) ) { return false ; } try { JavaClass [ ] superclassList = javaClass . getSuperClasses ( ) ; if ( superclassList != null ) { JavaClassAndMethod match = Hierarchy . findMethod ( superclassList , method . getName...
Determine if given method overrides a superclass or superinterface method .
153,825
public static String transformClassName ( String className ) { int lastDot = className . lastIndexOf ( '.' ) ; if ( lastDot >= 0 ) { String pkg = className . substring ( 0 , lastDot ) ; if ( ! isUnlikelyToBeRenamed ( pkg ) ) { className = className . substring ( lastDot + 1 ) ; } } return className ; }
Transform a class name by stripping its package name .
153,826
public static String transformMethodSignature ( String signature ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( '(' ) ; SignatureParser parser = new SignatureParser ( signature ) ; for ( Iterator < String > i = parser . parameterSignatureIterator ( ) ; i . hasNext ( ) ; ) { String param = i . next ( ) ;...
Transform a method signature to allow it to be compared even if any of its parameter types are moved to another package .
153,827
public static String transformSignature ( String signature ) { StringBuilder buf = new StringBuilder ( ) ; int lastBracket = signature . lastIndexOf ( '[' ) ; if ( lastBracket > 0 ) { buf . append ( signature . substring ( 0 , lastBracket + 1 ) ) ; signature = signature . substring ( lastBracket + 1 ) ; } if ( signatur...
Transform a field or method parameter signature to allow it to be compared even if it is moved to another package .
153,828
private void handleExceptions ( Subroutine subroutine , InstructionHandle pei , BasicBlock etb ) { etb . setExceptionThrower ( pei ) ; boolean sawUniversalExceptionHandler = false ; List < CodeExceptionGen > exceptionHandlerList = exceptionHandlerMap . getHandlerList ( pei ) ; if ( exceptionHandlerList != null ) { for ...
Add exception edges for given instruction .
153,829
private boolean isPEI ( InstructionHandle handle ) throws CFGBuilderException { Instruction ins = handle . getInstruction ( ) ; if ( ! ( ins instanceof ExceptionThrower ) ) { return false ; } if ( ins instanceof NEW ) { return false ; } if ( ins instanceof GETSTATIC ) { return false ; } if ( ins instanceof PUTSTATIC ) ...
Return whether or not the given instruction can throw exceptions .
153,830
private static boolean isMerge ( InstructionHandle handle ) { if ( handle . hasTargeters ( ) ) { InstructionTargeter [ ] targeterList = handle . getTargeters ( ) ; for ( InstructionTargeter targeter : targeterList ) { if ( targeter instanceof BranchInstruction ) { return true ; } } } return false ; }
Determine whether or not the given instruction is a control flow merge .
153,831
private CFG inlineAll ( ) throws CFGBuilderException { CFG result = new CFG ( ) ; Context rootContext = new Context ( null , topLevelSubroutine , result ) ; rootContext . mapBlock ( topLevelSubroutine . getEntry ( ) , result . getEntry ( ) ) ; rootContext . mapBlock ( topLevelSubroutine . getExit ( ) , result . getExit...
Inline all JSR subroutines into the top - level subroutine . This produces a complete CFG for the entire method in which all JSR subroutines are inlined .
153,832
public static void main ( String [ ] argv ) throws Exception { if ( argv . length != 1 ) { System . err . println ( "Usage: " + BetterCFGBuilder2 . class . getName ( ) + " <class file>" ) ; System . exit ( 1 ) ; } String methodName = SystemProperties . getProperty ( "cfgbuilder.method" ) ; JavaClass jclass = new ClassP...
Test driver .
153,833
public static XField createXField ( String className , Field field ) { String fieldName = field . getName ( ) ; String fieldSig = field . getSignature ( ) ; XField xfield = getExactXField ( className , fieldName , fieldSig , field . isStatic ( ) ) ; assert xfield . isResolved ( ) : "Could not exactly resolve " + xfield...
Create an XField object from a BCEL Field .
153,834
public static XMethod createXMethod ( InvokeInstruction invokeInstruction , ConstantPoolGen cpg ) { String className = invokeInstruction . getClassName ( cpg ) ; String methodName = invokeInstruction . getName ( cpg ) ; String methodSig = invokeInstruction . getSignature ( cpg ) ; if ( invokeInstruction instanceof INVO...
Create an XMethod object from an InvokeInstruction .
153,835
public static XMethod createXMethod ( PreorderVisitor visitor ) { JavaClass javaClass = visitor . getThisClass ( ) ; Method method = visitor . getMethod ( ) ; XMethod m = createXMethod ( javaClass , method ) ; return m ; }
Create an XMethod object from the method currently being visited by the given PreorderVisitor .
153,836
public static XField createXField ( PreorderVisitor visitor ) { JavaClass javaClass = visitor . getThisClass ( ) ; Field field = visitor . getField ( ) ; XField f = createXField ( javaClass , field ) ; return f ; }
Create an XField object from the field currently being visited by the given PreorderVisitor .
153,837
public XClass getXClass ( ClassDescriptor classDescriptor ) { try { IAnalysisCache analysisCache = Global . getAnalysisCache ( ) ; return analysisCache . getClassAnalysis ( XClass . class , classDescriptor ) ; } catch ( CheckedAnalysisException e ) { return null ; } }
Get the XClass object providing information about the class named by the given ClassDescriptor .
153,838
protected void work ( IWorkbenchPart part , final IResource resource , final List < WorkItem > resources ) { FindBugsJob runFindBugs = new StartedFromViewJob ( "Finding bugs in " + resource . getName ( ) + "..." , resource , resources , part ) ; runFindBugs . scheduleInteractive ( ) ; }
Run a FindBugs analysis on the given resource displaying a progress monitor .
153,839
public void setClasspath ( Path src ) { if ( classpath == null ) { classpath = src ; } else { classpath . append ( src ) ; } }
Set the classpath to use .
153,840
public void setClasspathRef ( Reference r ) { Path path = createClasspath ( ) ; path . setRefid ( r ) ; path . toString ( ) ; }
Adds a reference to a classpath defined elsewhere .
153,841
protected void checkParameters ( ) { if ( homeDir == null && classpath == null ) { throw new BuildException ( "either home attribute or " + "classpath attributes " + " must be defined for task <" + getTaskName ( ) + "/>" , getLocation ( ) ) ; } if ( pluginList != null ) { String [ ] pluginFileList = pluginList . list (...
Check that all required attributes have been set .
153,842
private void execFindbugs ( ) throws BuildException { System . out . println ( "Executing SpotBugs " + this . getClass ( ) . getSimpleName ( ) + " from ant task" ) ; createFindbugsEngine ( ) ; configureFindbugsEngine ( ) ; beforeExecuteJavaProcess ( ) ; if ( getDebug ( ) ) { log ( getFindbugsEngine ( ) . getCommandLine...
Create a new JVM to do the work .
153,843
public static void configureTrainingDatabases ( IFindBugsEngine findBugs ) throws IOException { if ( findBugs . emitTrainingOutput ( ) ) { String trainingOutputDir = findBugs . getTrainingOutputDir ( ) ; if ( ! new File ( trainingOutputDir ) . isDirectory ( ) ) { throw new IOException ( "Training output directory " + t...
Configure training databases .
153,844
public static boolean isDetectorEnabled ( IFindBugsEngine findBugs , DetectorFactory factory , int rankThreshold ) { if ( ! findBugs . getUserPreferences ( ) . isDetectorEnabled ( factory ) ) { return false ; } if ( ! factory . isEnabledForCurrentJRE ( ) ) { return false ; } if ( ! AnalysisContext . currentAnalysisCont...
Determines whether or not given DetectorFactory should be enabled .
153,845
public static Set < String > handleBugCategories ( String categories ) { Set < String > categorySet = new HashSet < > ( ) ; StringTokenizer tok = new StringTokenizer ( categories , "," ) ; while ( tok . hasMoreTokens ( ) ) { categorySet . add ( tok . nextToken ( ) ) ; } return categorySet ; }
Process - bugCategories option .
153,846
public static void processCommandLine ( TextUICommandLine commandLine , String [ ] argv , IFindBugsEngine findBugs ) throws IOException , FilterException { try { argv = commandLine . expandOptionFiles ( argv , true , true ) ; } catch ( HelpRequestedException e ) { showHelp ( commandLine ) ; } int argCount = 0 ; try { a...
Process the command line .
153,847
@ SuppressFBWarnings ( "DM_EXIT" ) public static void showHelp ( TextUICommandLine commandLine ) { showSynopsis ( ) ; ShowHelp . showGeneralOptions ( ) ; FindBugs . showCommandLineOptions ( commandLine ) ; System . exit ( 1 ) ; }
Show - help message .
153,848
@ SuppressFBWarnings ( "DM_EXIT" ) public static void runMain ( IFindBugsEngine findBugs , TextUICommandLine commandLine ) throws IOException { boolean verbose = ! commandLine . quiet ( ) ; try { findBugs . execute ( ) ; } catch ( InterruptedException e ) { assert false ; checkExitCodeFail ( commandLine , e ) ; throw n...
Given a fully - configured IFindBugsEngine and the TextUICommandLine used to configure it execute the analysis .
153,849
public static BugReporter configureBaselineFilter ( BugReporter bugReporter , String baselineFileName ) throws IOException , DocumentException { return new ExcludingHashesBugReporter ( bugReporter , baselineFileName ) ; }
Configure a baseline bug instance filter .
153,850
public void analyzeInstruction ( Instruction ins ) throws DataflowAnalysisException { if ( frame . isValid ( ) ) { try { ins . accept ( this ) ; } catch ( InvalidBytecodeException e ) { String message = "Invalid bytecode: could not analyze instr. " + ins + " at frame " + frame ; throw new DataflowAnalysisException ( me...
Analyze the given Instruction .
153,851
public int getNumWordsConsumed ( Instruction ins ) { int numWordsConsumed = ins . consumeStack ( cpg ) ; if ( numWordsConsumed == Const . UNPREDICTABLE ) { throw new InvalidBytecodeException ( "Unpredictable stack consumption" ) ; } return numWordsConsumed ; }
Get the number of words consumed by given instruction .
153,852
public int getNumWordsProduced ( Instruction ins ) { int numWordsProduced = ins . produceStack ( cpg ) ; if ( numWordsProduced == Const . UNPREDICTABLE ) { throw new InvalidBytecodeException ( "Unpredictable stack productions" ) ; } return numWordsProduced ; }
Get the number of words produced by given instruction .
153,853
public final void visitConversionInstruction ( ConversionInstruction obj ) { visitConversionInstruction2 ( obj ) ; if ( obj instanceof NULL2Z ) { visitNULL2Z ( ( NULL2Z ) obj ) ; } else if ( obj instanceof NONNULL2Z ) { visitNONNULL2Z ( ( NONNULL2Z ) obj ) ; } }
To allow for calls to visitNULL2Z and visitNONNULL2Z this method is made final . If you want to override it override visitConversionInstruction2 instead .
153,854
public void handleStoreInstruction ( StoreInstruction obj ) { try { int numConsumed = obj . consumeStack ( cpg ) ; if ( numConsumed == Const . UNPREDICTABLE ) { throw new InvalidBytecodeException ( "Unpredictable stack consumption" ) ; } int index = obj . getIndex ( ) ; while ( numConsumed -- > 0 ) { Value value = fram...
Handler for all instructions which pop values from the stack and store them in a local variable . Note that two locals are stored into for long and double stores .
153,855
public void modelInstruction ( Instruction ins , int numWordsConsumed , int numWordsProduced , Value pushValue ) { if ( frame . getStackDepth ( ) < numWordsConsumed ) { try { throw new IllegalArgumentException ( " asked to pop " + numWordsConsumed + " stack elements but only " + frame . getStackDepth ( ) + " elements r...
Primitive to model the stack effect of a single instruction explicitly specifying the value to be pushed on the stack .
153,856
private void locateCodebasesRequiredForAnalysis ( IClassPath classPath , IClassPathBuilderProgress progress ) throws InterruptedException , IOException , ResourceNotFoundException { boolean foundJavaLangObject = false ; boolean foundFindBugsAnnotations = false ; boolean foundJSR305Annotations = false ; for ( Discovered...
Make an effort to find the codebases containing any files required for analysis .
153,857
private boolean probeCodeBaseForResource ( DiscoveredCodeBase discoveredCodeBase , String resourceName ) { ICodeBaseEntry resource = discoveredCodeBase . getCodeBase ( ) . lookupResource ( resourceName ) ; return resource != null ; }
Probe a codebase to see if a given source exists in that code base .
153,858
private void addWorkListItemsForClasspath ( LinkedList < WorkListItem > workList , String path ) { if ( path == null ) { return ; } StringTokenizer st = new StringTokenizer ( path , File . pathSeparator ) ; while ( st . hasMoreTokens ( ) ) { String entry = st . nextToken ( ) ; if ( DEBUG ) { System . out . println ( "S...
Add worklist items from given system classpath .
153,859
private void addWorkListItemsForExtDir ( LinkedList < WorkListItem > workList , String extDir ) { File dir = new File ( extDir ) ; File [ ] fileList = dir . listFiles ( ( FileFilter ) pathname -> { String path = pathname . getPath ( ) ; boolean isArchive = Archive . isArchiveFileName ( path ) ; return isArchive ; } ) ;...
Add worklist items from given extensions directory .
153,860
private void parseClassName ( ICodeBaseEntry entry ) { DataInputStream in = null ; try { InputStream resourceIn = entry . openResource ( ) ; if ( resourceIn == null ) { throw new NullPointerException ( "Got null resource" ) ; } in = new DataInputStream ( resourceIn ) ; ClassParserInterface parser = new ClassParser ( in...
Attempt to parse data of given resource in order to divine the real name of the class contained in the resource .
153,861
private void scanJarManifestForClassPathEntries ( LinkedList < WorkListItem > workList , ICodeBase codeBase ) throws IOException { ICodeBaseEntry manifestEntry = codeBase . lookupResource ( "META-INF/MANIFEST.MF" ) ; if ( manifestEntry == null ) { return ; } InputStream in = null ; try { in = manifestEntry . openResour...
Check a codebase for a Jar manifest to examine for Class - Path entries .
153,862
public void addCreatedResource ( Location location , Resource resource ) { resourceList . add ( resource ) ; locationToResourceMap . put ( location , resource ) ; }
Add a resource created within the analyzed method .
153,863
protected void syncUserPreferencesWithTable ( ) { TableItem [ ] itemList = availableFactoriesTableViewer . getTable ( ) . getItems ( ) ; UserPreferences currentProps = getCurrentProps ( ) ; for ( int i = 0 ; i < itemList . length ; i ++ ) { DetectorFactory factory = ( DetectorFactory ) itemList [ i ] . getData ( ) ; cu...
Disables all unchecked detector factories and enables checked factory detectors leaving those not in the table unmodified .
153,864
private Table createDetectorsTableViewer ( Composite parent , IProject project ) { final BugPatternTableSorter sorter = new BugPatternTableSorter ( this ) ; int tableStyle = SWT . BORDER | SWT . H_SCROLL | SWT . V_SCROLL | SWT . SINGLE | SWT . FULL_SELECTION | SWT . CHECK ; availableFactoriesTableViewer = CheckboxTable...
Build rule table viewer
153,865
private void populateAvailableRulesTable ( IProject project ) { List < DetectorFactory > allAvailableList = new ArrayList < > ( ) ; factoriesToBugAbbrev = new HashMap < > ( ) ; Iterator < DetectorFactory > iterator = DetectorFactoryCollection . instance ( ) . factoryIterator ( ) ; while ( iterator . hasNext ( ) ) { Det...
Populate the rule table
153,866
public void mergeWith ( ReturnPathType fact ) { if ( fact . isTop ( ) ) { return ; } else if ( this . isTop ( ) ) { this . copyFrom ( fact ) ; } else { if ( fact . type == CAN_RETURN_NORMALLY ) { this . type = CAN_RETURN_NORMALLY ; } } }
Merge this fact with given fact .
153,867
public void handleAbout ( ApplicationEvent ae ) { if ( mainApp != null ) { ae . setHandled ( true ) ; javax . swing . SwingUtilities . invokeLater ( ( ) -> mainApp . about ( ) ) ; } else { throw new IllegalStateException ( "handleAbout: " + "MyApp instance detached from listener" ) ; } }
over from another platform .
153,868
public BleIllegalOperationException handleMismatchData ( BluetoothGattCharacteristic characteristic , int neededProperties ) { RxBleLog . w ( messageCreator . createMismatchMessage ( characteristic , neededProperties ) ) ; return null ; }
This method logs a warning .
153,869
public static RxBleClient getRxBleClient ( Context context ) { SampleApplication application = ( SampleApplication ) context . getApplicationContext ( ) ; return application . rxBleClient ; }
In practise you will use some kind of dependency injection pattern .
153,870
public Completable checkAnyPropertyMatches ( final BluetoothGattCharacteristic characteristic , final int neededProperties ) { return Completable . fromAction ( new Action ( ) { public void run ( ) { final int characteristicProperties = characteristic . getProperties ( ) ; if ( ( characteristicProperties & neededProper...
This method checks whether the supplied characteristic possesses properties supporting the requested kind of operation specified by the supplied bitmask .
153,871
public static void handleException ( final Activity context , final BleScanException exception ) { final String text ; final int reason = exception . getReason ( ) ; if ( reason == BleScanException . UNDOCUMENTED_SCAN_THROTTLE ) { text = getUndocumentedScanThrottleErrorMessage ( context , exception . getRetryDateSugges...
Show toast with error message appropriate to exception reason .
153,872
private Single < BluetoothGatt > getConnectedBluetoothGatt ( ) { return Single . create ( new SingleOnSubscribe < BluetoothGatt > ( ) { public void subscribe ( final SingleEmitter < BluetoothGatt > emitter ) throws Exception { final DisposableSingleObserver < BluetoothGatt > disposableGattObserver = getBluetoothGattAnd...
Emits BluetoothGatt and completes after connection is established .
153,873
private ObservableTransformer < RxBleInternalScanResult , RxBleInternalScanResult > repeatedWindowTransformer ( @ IntRange ( from = 0 , to = 4999 ) final int windowInMillis ) { final long repeatCycleTimeInMillis = TimeUnit . SECONDS . toMillis ( 5 ) ; final long delayToNextWindow = Math . max ( repeatCycleTimeInMillis ...
A convenience method for running a scan for a period of time and repeat in five seconds intervals .
153,874
private boolean matchesServiceUuids ( ParcelUuid uuid , ParcelUuid parcelUuidMask , List < ParcelUuid > uuids ) { if ( uuid == null ) { return true ; } if ( uuids == null ) { return false ; } for ( ParcelUuid parcelUuid : uuids ) { UUID uuidMask = parcelUuidMask == null ? null : parcelUuidMask . getUuid ( ) ; if ( matc...
Check if the uuid pattern is contained in a list of parcel uuids .
153,875
private boolean isPermissionGranted ( String permission ) { if ( permission == null ) { throw new IllegalArgumentException ( "permission is null" ) ; } return context . checkPermission ( permission , android . os . Process . myPid ( ) , Process . myUid ( ) ) == PackageManager . PERMISSION_GRANTED ; }
Copied from android . support . v4 . content . ContextCompat for backwards compatibility
153,876
private static int parseServiceUuid ( byte [ ] scanRecord , int currentPos , int dataLength , int uuidLength , List < ParcelUuid > serviceUuids ) { while ( dataLength > 0 ) { byte [ ] uuidBytes = extractBytes ( scanRecord , currentPos , uuidLength ) ; serviceUuids . add ( parseUuidFrom ( uuidBytes ) ) ; dataLength -= u...
Parse service UUIDs .
153,877
private static byte [ ] extractBytes ( byte [ ] scanRecord , int start , int length ) { byte [ ] bytes = new byte [ length ] ; System . arraycopy ( scanRecord , start , bytes , 0 , length ) ; return bytes ; }
Helper method to extract bytes from byte array .
153,878
private static int unsignedBytesToInt ( byte b0 , byte b1 , byte b2 , byte b3 ) { return ( unsignedByteToInt ( b0 ) + ( unsignedByteToInt ( b1 ) << 8 ) ) + ( unsignedByteToInt ( b2 ) << 16 ) + ( unsignedByteToInt ( b3 ) << 24 ) ; }
Convert signed bytes to a 32 - bit unsigned int .
153,879
private static float bytesToFloat ( byte b0 , byte b1 ) { int mantissa = unsignedToSigned ( unsignedByteToInt ( b0 ) + ( ( unsignedByteToInt ( b1 ) & 0x0F ) << 8 ) , 12 ) ; int exponent = unsignedToSigned ( unsignedByteToInt ( b1 ) >> 4 , 4 ) ; return ( float ) ( mantissa * Math . pow ( 10 , exponent ) ) ; }
Convert signed bytes to a 16 - bit short float value .
153,880
private static float bytesToFloat ( byte b0 , byte b1 , byte b2 , byte b3 ) { int mantissa = unsignedToSigned ( unsignedByteToInt ( b0 ) + ( unsignedByteToInt ( b1 ) << 8 ) + ( unsignedByteToInt ( b2 ) << 16 ) , 24 ) ; return ( float ) ( mantissa * Math . pow ( 10 , b3 ) ) ; }
Convert signed bytes to a 32 - bit short float value .
153,881
private static int unsignedToSigned ( int unsigned , int size ) { if ( ( unsigned & ( 1 << size - 1 ) ) != 0 ) { unsigned = - 1 * ( ( 1 << size - 1 ) - ( unsigned & ( ( 1 << size - 1 ) - 1 ) ) ) ; } return unsigned ; }
Convert an unsigned integer value to a two s - complement encoded signed value .
153,882
private static < T > ObservableTransformer < T , T > repeatAfterCompleted ( ) { return observable -> observable . repeatWhen ( completedNotification -> completedNotification ) ; }
A convenience function creating a transformer that will repeat the source observable whenever it will complete
153,883
public static void updateLogOptions ( LogOptions logOptions ) { LoggerSetup oldLoggerSetup = RxBleLog . loggerSetup ; LoggerSetup newLoggerSetup = oldLoggerSetup . merge ( logOptions ) ; d ( "Received new options (%s) and merged with old setup: %s. New setup: %s" , logOptions , oldLoggerSetup , newLoggerSetup ) ; RxBle...
Method to update current logger setup with new LogOptions . Only set options will be updated . Options that were not set or set to null on the LogOptions will not update the current setup leaving the previous values untouched .
153,884
private void updateUI ( BluetoothGattCharacteristic characteristic ) { connectButton . setText ( characteristic != null ? R . string . disconnect : R . string . connect ) ; readButton . setEnabled ( hasProperty ( characteristic , BluetoothGattCharacteristic . PROPERTY_READ ) ) ; writeButton . setEnabled ( hasProperty (...
This method updates the UI to a proper state .
153,885
private static Single < Boolean > checkPermissionUntilGranted ( final LocationServicesStatus locationServicesStatus , Scheduler timerScheduler ) { return Observable . interval ( 0 , 1L , TimeUnit . SECONDS , timerScheduler ) . takeWhile ( new Predicate < Long > ( ) { public boolean test ( Long timer ) { return ! locati...
Observable that emits true if the permission was granted on the time of subscription
153,886
@ TargetApi ( Build . VERSION_CODES . HONEYCOMB ) protected View onCreateView ( View parent , String name , AttributeSet attrs ) throws ClassNotFoundException { return mCalligraphyFactory . onViewCreated ( super . onCreateView ( parent , name , attrs ) , getContext ( ) , attrs ) ; }
The LayoutInflater onCreateView is the fourth port of call for LayoutInflation . BUT only for none CustomViews .
153,887
public static CharSequence applyTypefaceSpan ( CharSequence s , Typeface typeface ) { if ( s != null && s . length ( ) > 0 ) { if ( ! ( s instanceof Spannable ) ) { s = new SpannableString ( s ) ; } ( ( Spannable ) s ) . setSpan ( TypefaceUtils . getSpan ( typeface ) , 0 , s . length ( ) , Spanned . SPAN_EXCLUSIVE_EXCL...
Applies a custom typeface span to the text .
153,888
public static boolean applyFontToTextView ( final TextView textView , final Typeface typeface , boolean deferred ) { if ( textView == null || typeface == null ) return false ; textView . setPaintFlags ( textView . getPaintFlags ( ) | Paint . SUBPIXEL_TEXT_FLAG | Paint . ANTI_ALIAS_FLAG ) ; textView . setTypeface ( type...
Applies a Typeface to a TextView if deferred its recommend you don t call this multiple times as this adds a TextWatcher .
153,889
static String pullFontPathFromView ( Context context , AttributeSet attrs , int [ ] attributeId ) { if ( attributeId == null || attrs == null ) return null ; final String attributeName ; try { attributeName = context . getResources ( ) . getResourceEntryName ( attributeId [ 0 ] ) ; } catch ( Resources . NotFoundExcepti...
Tries to pull the Custom Attribute directly from the TextView .
153,890
static String pullFontPathFromStyle ( Context context , AttributeSet attrs , int [ ] attributeId ) { if ( attributeId == null || attrs == null ) return null ; final TypedArray typedArray = context . obtainStyledAttributes ( attrs , attributeId ) ; if ( typedArray != null ) { try { String fontFromAttribute = typedArray ...
Tries to pull the Font Path from the View Style as this is the next decendent after being defined in the View s xml .
153,891
static String pullFontPathFromTextAppearance ( final Context context , AttributeSet attrs , int [ ] attributeId ) { if ( attributeId == null || attrs == null ) { return null ; } int textAppearanceId = - 1 ; final TypedArray typedArrayAttr = context . obtainStyledAttributes ( attrs , ANDROID_ATTR_TEXT_APPEARANCE ) ; if ...
Tries to pull the Font Path from the Text Appearance .
153,892
static boolean canCheckForV7Toolbar ( ) { if ( sToolbarCheck == null ) { try { Class . forName ( "android.support.v7.widget.Toolbar" ) ; sToolbarCheck = Boolean . TRUE ; } catch ( ClassNotFoundException e ) { sToolbarCheck = Boolean . FALSE ; } } return sToolbarCheck ; }
See if the user has added appcompat - v7 this is done at runtime so we only check once .
153,893
static boolean canAddV7AppCompatViews ( ) { if ( sAppCompatViewCheck == null ) { try { Class . forName ( "android.support.v7.widget.AppCompatTextView" ) ; sAppCompatViewCheck = Boolean . TRUE ; } catch ( ClassNotFoundException e ) { sAppCompatViewCheck = Boolean . FALSE ; } } return sAppCompatViewCheck ; }
See if the user has added appcompat - v7 with AppCompatViews
153,894
private static void addAppCompatViews ( ) { DEFAULT_STYLES . put ( android . support . v7 . widget . AppCompatTextView . class , android . R . attr . textViewStyle ) ; DEFAULT_STYLES . put ( android . support . v7 . widget . AppCompatButton . class , android . R . attr . buttonStyle ) ; DEFAULT_STYLES . put ( android ....
AppCompat will inflate special versions of views for Material tinting etc this adds those classes to the style lookup map
153,895
static CalligraphyActivityFactory get ( Activity activity ) { if ( ! ( activity . getLayoutInflater ( ) instanceof CalligraphyLayoutInflater ) ) { throw new RuntimeException ( "This activity does not wrap the Base Context! See CalligraphyContextWrapper.wrap(Context)" ) ; } return ( CalligraphyActivityFactory ) activity...
Get the Calligraphy Activity Fragment Instance to allow callbacks for when views are created .
153,896
protected static int [ ] getStyleForTextView ( TextView view ) { final int [ ] styleIds = new int [ ] { - 1 , - 1 } ; if ( isActionBarTitle ( view ) ) { styleIds [ 0 ] = android . R . attr . actionBarStyle ; styleIds [ 1 ] = android . R . attr . titleTextStyle ; } else if ( isActionBarSubTitle ( view ) ) { styleIds [ 0...
Some styles are in sub styles such as actionBarTextStyle etc ..
153,897
protected static boolean matchesResourceIdName ( View view , String matches ) { if ( view . getId ( ) == View . NO_ID ) return false ; final String resourceEntryName = view . getResources ( ) . getResourceEntryName ( view . getId ( ) ) ; return resourceEntryName . equalsIgnoreCase ( matches ) ; }
Use to match a view against a potential view id . Such as ActionBar title etc .
153,898
public View onViewCreated ( View view , Context context , AttributeSet attrs ) { if ( view != null && view . getTag ( R . id . calligraphy_tag_id ) != Boolean . TRUE ) { onViewCreatedInternal ( view , context , attrs ) ; view . setTag ( R . id . calligraphy_tag_id , Boolean . TRUE ) ; } return view ; }
Handle the created view
153,899
private String resolveFontPath ( Context context , AttributeSet attrs ) { String textViewFont = CalligraphyUtils . pullFontPathFromView ( context , attrs , mAttributeId ) ; if ( TextUtils . isEmpty ( textViewFont ) ) { textViewFont = CalligraphyUtils . pullFontPathFromStyle ( context , attrs , mAttributeId ) ; } if ( T...
Resolving font path from xml attrs style attrs or text appearance